from fastapi.security import OAuth2PasswordRequestForm

from app.core.responses import Response
from app.core.exceptions import ApiException
from fastapi import APIRouter
from modules.admin.services.auth import *
from modules.admin.schemas.user import User
from modules.admin.services.auth import Authenticate
from schemas.auth import Login

auth_service = Authenticate()

router = APIRouter(prefix="/auth")


@router.post("/token", summary="登录")
async def login_for_access_token(form_data: Login):
    user = auth_service.authenticate_user(form_data.username, form_data.password)
    if not user:
        raise ApiException("密码错误", code=400)
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.id}, expires_delta=access_token_expires
    )
    return Response({"token": access_token})


@router.get("/current_user", summary="用户信息")
async def detail_user(current_user: User = Depends(get_current_active_user)):
    return Response.success(current_user, "success")
